package com.meida.module.bus.provider.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.DateUtils;
import com.meida.common.utils.RedisUtils;
import com.meida.module.bus.client.entity.BusVipUser;
import com.meida.module.bus.client.entity.VipConfig;
import com.meida.module.bus.client.entity.VipType;
import com.meida.module.bus.provider.mapper.VipTypeMapper;
import com.meida.module.bus.provider.service.*;
import com.meida.module.bus.provider.util.ConvertUtil;
import com.meida.module.system.client.entity.SysConfig;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * vip表 实现类
 *
 * @author flyme
 * @date 2019-06-24
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusVipTypeServiceImpl extends BaseServiceImpl<VipTypeMapper, VipType> implements BusVipTypeService {

    @Autowired
    VipConfigService vipConfigService;

    @Autowired
    BusVipUserService busVipUserService;

    @Resource
    private RedisUtils redisUtils;

    @Autowired
    private RebateLogicService rebateLogicService;
    @Resource
    private AppUserExtraService appUserService;
    @Autowired
    BusConfigService busConfigService;

    @Override
    public ResultBody beforeListEntityMap(CriteriaQuery<VipType> cq, VipType vipType, EntityMap requestMap) {
        cq.select("type.vipTypeId", "type.vipName", "type.prePrice", "type.oriPrice", "type.vipLogo");
        return super.beforeListEntityMap(cq, vipType, requestMap);
    }

    @Override
    public ResultBody afterListEntityMap(CriteriaQuery<VipType> cq, List<EntityMap> data, ResultBody resultBody) {
        for (EntityMap map : data) {
            Long vipTypeId = map.getLong("vipTypeId");
            VipConfig vipConfig = vipConfigService.getOne(new QueryWrapper<VipConfig>().lambda().eq(VipConfig::getVipTypeId, vipTypeId));
            if (FlymeUtils.isNotEmpty(vipConfig)) {
                //详情
                map.put("configTitle", vipConfig.getConfigTitle());
                map.put("configContent", vipConfig.getConfigContent());
            }
        }
        return resultBody;
    }


    @SneakyThrows
    @Override
    public Object getVipDetail(String vipTypeId) {
        VipType vipType = getById(vipTypeId);
        Map<String, Object> map = ConvertUtil.objectToMap(vipType);
        VipConfig vipConfig = vipConfigService.getOne(new QueryWrapper<VipConfig>().lambda().eq(VipConfig::getVipTypeId, vipTypeId));
        if (FlymeUtils.isNotEmpty(vipConfig)) {
            //商品详情
            Map<String, Object> detail = ConvertUtil.objectToMap(vipConfig);
            map.putAll(detail);
        }
        return map;
    }

    @Override
    public boolean buyVip(Long vipTypeId) {
        Long userId = OpenHelper.getUserId();
        saveVipUser(vipTypeId, userId);
        return true;
    }

    private void saveVipUser(Long vipTypeId, Long userId) {
        BusVipUser vipUser = busVipUserService.getByUserId(userId);
        VipType vipType = this.getById(vipTypeId);
        Integer month = vipType.getDuration();
        if (FlymeUtils.isEmpty(vipUser)) {
            if (vipTypeId > 0) {
                String expiryDate = DateUtils.format(DateUtils.plusMonths(month));
                vipUser = new BusVipUser();
                vipUser.setUserId(userId);
                vipUser.setVipTypeId(vipTypeId);
                vipUser.setExpiryDate(DateUtils.parseDate(expiryDate));
                if (vipTypeId > 1) {
                    List<SysConfig> sysConfigs = busConfigService.listByType("partner");
                    String configVal = sysConfigs.get(0).getConfigVal();
                    JSONObject object = JSON.parseObject(configVal);
                    String group = object.getString("group");
                    Integer member = object.getInteger("member");
                    SysConfig currentGroup = busConfigService.getById(29);
                    String maxGroupNum = currentGroup.getConfigVal();
                    if (StrUtil.isEmpty(maxGroupNum)) {
                        vipUser.setGroupNum(group.substring(0, 2) + 1);
                    } else {
                        String[] split = maxGroupNum.split("-");
                        int i = Integer.parseInt(split[1]);
                        if (i < member) {
                            vipUser.setGroupNum(split[0] + "-" + (i + 1));
                        } else {
                            vipUser.setGroupNum(group.replace(split[0] + "-", "").substring(0, 2) + 1);
                        }
                    }
                    currentGroup.setConfigVal(vipUser.getGroupNum());
                    busConfigService.updateById(currentGroup);
                }
                busVipUserService.save(vipUser);
            }

        } else {
            String date = Optional.ofNullable(DateUtils.formatDate(vipUser.getExpiryDate())).orElse(DateUtils.formatDate());
            String expiryDate = DateUtils.plusMonth(DateUtils.parseLocalDate(date), month);
            vipUser.setVipTypeId(vipTypeId);
            vipUser.setExpiryDate(DateUtils.parseDate(expiryDate));
            if (vipTypeId > 1) {
                if (StrUtil.isEmpty(vipUser.getGroupNum())) {
                    List<SysConfig> sysConfigs = busConfigService.listByType("partner");
                    String configVal = sysConfigs.get(0).getConfigVal();
                    JSONObject object = JSON.parseObject(configVal);
                    String group = object.getString("group");
                    Integer member = object.getInteger("member");
                    SysConfig currentGroup = busConfigService.getById(29);
                    String maxGroupNum = currentGroup.getConfigVal();
                    if (StrUtil.isEmpty(maxGroupNum)) {
                        vipUser.setGroupNum(group.substring(0, 2) + 1);
                    } else {
                        String[] split = maxGroupNum.split("-");
                        int i = Integer.parseInt(split[1]);
                        if (i < member) {
                            vipUser.setGroupNum(split[0] + "-" + (i + 1));
                        } else {
                            vipUser.setGroupNum(group.replace(split[0] + "-", "").substring(0, 2) + 1);
                        }
                    }
                    currentGroup.setConfigVal(vipUser.getGroupNum());
                    busConfigService.updateById(currentGroup);
                }
            }
            if (vipTypeId == 0) {
                busVipUserService.removeById(vipUser.getVipId());
            } else {
                busVipUserService.updateById(vipUser);
            }
        }
        if (vipTypeId > 0) {
            EntityMap payUser = appUserService.getAppUserVipInfo(userId);
            EntityMap superiorUser = ObjectUtil.isEmpty(payUser.get("inviterId")) ? null : appUserService.getAppUserVipInfo(payUser.getLong("inviterId"));
            rebateLogicService.buyVip(vipType, payUser, superiorUser, vipUser);
        }
    }

    @Override
    public Object buyVip(Long vipTypeId, Long userId) {
        if (null == vipTypeId || null == userId) {
            return ResultBody.failed("非法参数");
        }
        saveVipUser(vipTypeId, userId);
        return ResultBody.ok("修改用户身份");
    }


}

